package p.ithorns.framework.common.mmap;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;

/**
 * MappedByteBufferReader
 *
 * @author ithorns
 * @version 1.0
 * @date 2021/11/7 0:29
 */
public class MappedReader implements MappedCleanable {

    private static final Logger log = LoggerFactory.getLogger(MappedReader.class);

    private static final FileChannel.MapMode MAP_MODE = FileChannel.MapMode.READ_ONLY;

    public byte[] read(String file) {
        try (
                FileChannel fc = FileChannel.open(Paths.get(file))
        ) {
            long fileSize = fc.size();
            MappedByteBuffer byteBuffer = fc.map(MAP_MODE, 0, fileSize);
            byte[] bytes = new byte[(int) fileSize];
            byteBuffer.get(bytes);

            byteBuffer.clear();
            clean(byteBuffer);
            return bytes;
        } catch (Exception e) {
            throw new RuntimeException("MappedReader读取数据失败.", e);
        }
    }

}